package com.totsp.conference.data;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public final class DataHelper {

	private static final String SPEAKERS_URL = "http://www.devnexus.com/s/speakers.json";
	private static final String PRESENTATIONS_URL = "http://www.devnexus.com/s/presentations.json";

	private DataHelper() {
	}

	// NOTE these methods should always be called from outside the UI thread (AsyncTask is a good idea)
	
	public static ArrayList<Speaker> getSpeakers() {
		ArrayList<Speaker> speakers = new ArrayList<Speaker>();

		HttpHelper client = new HttpHelper();
		String jsonString = client.performGet(SPEAKERS_URL);

		try {
			JSONObject root = new JSONObject(jsonString);
			JSONObject speakerList = root.getJSONObject("speakerList");
			// System.out.println("json  " + json.toString(2));
			JSONArray list = speakerList.getJSONArray("speaker");
			for (int i = 0; i < list.length(); i++) {
				JSONObject speaker = list.getJSONObject(i);
				int id = speaker.getInt("id");
				String fName = speaker.getString("firstName");
				String lName = speaker.getString("lastName");
				String bio = speaker.getString("bio");
				speakers.add(new Speaker(id, fName, lName, bio));
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return speakers;
	}

	public static ArrayList<Presentation> getPresentations() {
		ArrayList<Presentation> presentations = new ArrayList<Presentation>();

		HttpHelper client = new HttpHelper();
		String jsonString = client.performGet(PRESENTATIONS_URL);

		try {
			JSONObject root = new JSONObject(jsonString);
			JSONObject presentationList = root
					.getJSONObject("presentationList");
			// System.out.println("json  " + json.toString(2));
			JSONArray list = presentationList.getJSONArray("presentation");
			for (int i = 0; i < list.length(); i++) {
				JSONObject presentation = list.getJSONObject(i);
				int id = presentation.getInt("id");
				String title = presentation.getString("title");
				String description = presentation.getString("description");
				String link = presentation.getString("presentationLink");
				JSONObject speaker = presentation.getJSONObject("speaker");
				int spkrId = speaker.getInt("id");
				String fName = speaker.getString("firstName");
				String lName = speaker.getString("lastName");
				String bio = speaker.getString("bio");
				presentations.add(new Presentation(id, title, description,
						link, new Speaker(spkrId, fName, lName, bio)));
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return presentations;
	}
}
